package com.termux.app.api;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import com.termux.R;
import com.termux.app.TermuxActivity;
import com.termux.shared.logger.Logger;
import com.termux.shared.termux.TermuxConstants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TCP Socket服务器，用于接收Python客户端的请求并直接返回结果
 * 
 * 监听端口: 默认 12345（可通过环境变量 PYTHON_API_SOCKET_PORT 配置）
 * 协议: JSON格式
 * 
 * 请求格式:
 * {
 *   "action": "get_device_info",
 *   "message": "可选消息",
 *   "title": "可选标题",
 *   "data": "可选数据"
 * }
 * 
 * 响应格式:
 * {
 *   "status": "success" | "error",
 *   "data": "返回的数据"
 * }
 */
public class PythonApiSocketService extends Service {
    
    private static final String LOG_TAG = "PythonApiSocketService";
    private static final int DEFAULT_PORT = 12345;
    
    private ServerSocket serverSocket;
    private ExecutorService executorService;
    private boolean isRunning = false;
    private int serverPort = DEFAULT_PORT;
    private Handler mainHandler;
    private static final String CHANNEL_ID = "python_api_tcp_channel";
    
    @Override
    public void onCreate() {
        super.onCreate();
        Logger.logInfo(LOG_TAG, "PythonApiSocketService onCreate");
        
        // 创建主线程Handler用于显示UI
        mainHandler = new Handler(Looper.getMainLooper());
        
        // 创建通知渠道
        createNotificationChannel();
        
        // 从环境变量或配置中获取端口号
        String portStr = System.getenv("PYTHON_API_SOCKET_PORT");
        if (portStr != null) {
            try {
                serverPort = Integer.parseInt(portStr);
            } catch (NumberFormatException e) {
                Logger.logWarn(LOG_TAG, "Invalid port in PYTHON_API_SOCKET_PORT, using default: " + DEFAULT_PORT);
            }
        }
        
        executorService = Executors.newCachedThreadPool();
        startServer();
    }
    
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "Python API TCP Notifications",
                NotificationManager.IMPORTANCE_DEFAULT
            );
            channel.setDescription("来自 Python TCP Socket 的通知");
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logger.logInfo(LOG_TAG, "PythonApiSocketService onStartCommand");
        return START_STICKY; // 服务被杀死后自动重启
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null; // 不需要绑定
    }
    
    private void startServer() {
        executorService.execute(() -> {
            try {
                serverSocket = new ServerSocket(serverPort);
                isRunning = true;
                Logger.logInfo(LOG_TAG, "Python API Socket Server started on port " + serverPort);
                
                while (isRunning) {
                    try {
                        Socket clientSocket = serverSocket.accept();
                        Logger.logDebug(LOG_TAG, "New client connected: " + clientSocket.getRemoteSocketAddress());
                        
                        // 为每个客户端创建独立的处理线程
                        executorService.execute(() -> handleClient(clientSocket));
                    } catch (IOException e) {
                        if (isRunning) {
                            Logger.logError(LOG_TAG, "Error accepting client connection: " + e.getMessage());
                        }
                    }
                }
            } catch (IOException e) {
                Logger.logError(LOG_TAG, "Failed to start socket server: " + e.getMessage());
                e.printStackTrace();
            }
        });
    }
    
    private void handleClient(Socket clientSocket) {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true)) {
            
            // 读取客户端请求
            StringBuilder requestBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                requestBuilder.append(line);
                // 简单的结束标记，实际可以使用更复杂的协议
                if (line.trim().isEmpty() && requestBuilder.length() > 0) {
                    break;
                }
            }
            
            String requestJson = requestBuilder.toString().trim();
            Logger.logDebug(LOG_TAG, "Received request: " + requestJson);
            
            // 解析请求并处理
            JSONObject response = processRequest(requestJson);
            
            // 发送响应
            String responseJson = response.toString();
            writer.println(responseJson);
            writer.flush();
            
            Logger.logDebug(LOG_TAG, "Sent response: " + responseJson);
            
        } catch (IOException e) {
            Logger.logError(LOG_TAG, "Error handling client: " + e.getMessage());
        } catch (Exception e) {
            Logger.logError(LOG_TAG, "Unexpected error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                Logger.logError(LOG_TAG, "Error closing client socket: " + e.getMessage());
            }
        }
    }
    
    private JSONObject processRequest(String requestJson) {
        JSONObject response = new JSONObject();
        
        try {
            JSONObject request = new JSONObject(requestJson);
            String action = request.optString("action", "");
            
            Logger.logInfo(LOG_TAG, "Processing action: " + action);
            
            switch (action) {
                case "show_toast":
                    String message = request.optString("message", "");
                    if (!message.isEmpty()) {
                        // 通过Handler在主线程显示Toast
                        final String toastMessage = message;
                        mainHandler.post(() -> {
                            Toast.makeText(PythonApiSocketService.this, toastMessage, Toast.LENGTH_LONG).show();
                        });
                        response.put("status", "success");
                        response.put("data", "Toast已显示: " + message);
                        Logger.logInfo(LOG_TAG, "Toast shown: " + message);
                    } else {
                        response.put("status", "error");
                        response.put("data", "未提供消息内容");
                    }
                    break;
                    
                case "get_device_info":
                    String deviceInfo = getDeviceInfo();
                    response.put("status", "success");
                    response.put("data", deviceInfo);
                    break;
                    
                case "calculate":
                    String expression = request.optString("data", "");
                    if (!expression.isEmpty()) {
                        String result = performCalculation(expression);
                        response.put("status", "success");
                        response.put("data", result);
                    } else {
                        response.put("status", "error");
                        response.put("data", "未提供计算表达式");
                    }
                    break;
                    
                case "notification":
                    String title = request.optString("title", "Python 通知");
                    String notificationMessage = request.optString("message", "");
                    if (!notificationMessage.isEmpty()) {
                        showNotification(title, notificationMessage);
                        response.put("status", "success");
                        response.put("data", "通知已发送: " + notificationMessage);
                        Logger.logInfo(LOG_TAG, "Notification sent: " + title + " - " + notificationMessage);
                    } else {
                        response.put("status", "error");
                        response.put("data", "未提供通知消息");
                    }
                    break;
                    
                default:
                    response.put("status", "error");
                    response.put("data", "未知的操作: " + action);
            }
            
        } catch (JSONException e) {
            Logger.logError(LOG_TAG, "JSON parsing error: " + e.getMessage());
            try {
                response.put("status", "error");
                response.put("data", "JSON解析错误: " + e.getMessage());
            } catch (JSONException ex) {
                // 忽略
            }
        } catch (Exception e) {
            Logger.logError(LOG_TAG, "Error processing request: " + e.getMessage());
            try {
                response.put("status", "error");
                response.put("data", "处理请求时出错: " + e.getMessage());
            } catch (JSONException ex) {
                // 忽略
            }
        }
        
        return response;
    }
    
    private String getDeviceInfo() {
        StringBuilder info = new StringBuilder();
        info.append("设备型号: ").append(Build.MODEL).append("\n");
        info.append("Android版本: ").append(Build.VERSION.RELEASE).append("\n");
        info.append("SDK版本: ").append(Build.VERSION.SDK_INT).append("\n");
        info.append("制造商: ").append(Build.MANUFACTURER).append("\n");
        return info.toString();
    }
    
    private String performCalculation(String expression) {
        try {
            expression = expression.replaceAll("\\s+", "");
            
            if (expression.contains("+")) {
                String[] parts = expression.split("\\+");
                if (parts.length == 2) {
                    double a = Double.parseDouble(parts[0]);
                    double b = Double.parseDouble(parts[1]);
                    return String.valueOf(a + b);
                }
            } else if (expression.contains("-") && !expression.startsWith("-")) {
                String[] parts = expression.split("-");
                if (parts.length == 2) {
                    double a = Double.parseDouble(parts[0]);
                    double b = Double.parseDouble(parts[1]);
                    return String.valueOf(a - b);
                }
            } else if (expression.contains("*")) {
                String[] parts = expression.split("\\*");
                if (parts.length == 2) {
                    double a = Double.parseDouble(parts[0]);
                    double b = Double.parseDouble(parts[1]);
                    return String.valueOf(a * b);
                }
            } else if (expression.contains("/")) {
                String[] parts = expression.split("/");
                if (parts.length == 2) {
                    double a = Double.parseDouble(parts[0]);
                    double b = Double.parseDouble(parts[1]);
                    if (b == 0) {
                        return "错误: 除数不能为0";
                    }
                    return String.valueOf(a / b);
                }
            }
            
            return "错误: 不支持的表达式格式";
        } catch (Exception e) {
            return "错误: " + e.getMessage();
        }
    }
    
    private void showNotification(String title, String message) {
        try {
            NotificationManager notificationManager = 
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            
            if (notificationManager == null) {
                Logger.logError(LOG_TAG, "NotificationManager is null");
                return;
            }
            
            // 创建点击通知后打开的 Intent
            Intent intent = new Intent(this, TermuxActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, intent, 
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
            );
            
            // 创建通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);
            
            notificationManager.notify((int) System.currentTimeMillis(), builder.build());
            Logger.logInfo(LOG_TAG, "Notification created successfully");
        } catch (Exception e) {
            Logger.logError(LOG_TAG, "Failed to show notification: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.logInfo(LOG_TAG, "PythonApiSocketService onDestroy");
        isRunning = false;
        
        if (serverSocket != null && !serverSocket.isClosed()) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                Logger.logError(LOG_TAG, "Error closing server socket: " + e.getMessage());
            }
        }
        
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}

